package com.hdq.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdq.mapper.CouponMapper;
import com.hdq.result.PageResult;
import com.hdq.service.CouponService;
import com.hdq.websocket.WebSocketServer;
import dto.CouponRequestDTO;
import entity.Coupon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class CouponTask {

    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private CouponService couponService;
    private final static String sid = "coupon";
    @Autowired
    private ObjectMapper objectMapper;

    @Scheduled(cron = "0/59 * * * * ?")
    public void checkExpiredCoupon() throws JsonProcessingException {
//        查询是否存在优惠卷未开始的
        List<Coupon> coupons2 = couponMapper.selectByNotStart();
        setCouponStatus(coupons2,0,"优惠券未开始");
//        查询是否存在进行中的优惠卷
        List<Coupon> coupons3 = couponMapper.selectByStart();
        setCouponStatus(coupons3,1,"优惠券进行中");
        // 查询是否存在优惠券过期
        List<Coupon> coupons1 = couponMapper.selectByExpired();
        setCouponStatus(coupons1,2,"优惠券已过期");

        String message = webSocketServer.processClientRequest(sid);
        if(message!=null){
            CouponRequestDTO couponRequestDTO = objectMapper.readValue(message, CouponRequestDTO.class);
            if (couponRequestDTO.getAction().equals("getCouponData")) {
                Integer page = couponRequestDTO.getPage();
                Integer pageSize = couponRequestDTO.getPageSize();
                PageResult list = couponService.selectByPage(page, pageSize);
                String json_list = objectMapper.writeValueAsString(list);
                webSocketServer.sendToAllClient(json_list);
            }
        }

    }


    public void setCouponStatus(List<Coupon> coupons,Integer status,String title){
        if (coupons.size() > 0 && !coupons.isEmpty()) {
            log.info(title);
//            将status设置状态
            for (Coupon coupon : coupons) {
                coupon.setStatus(status);
                couponMapper.update(coupon);
            }
        }
    }
}
